package client.gui;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EtchedBorder;

public class UserList extends JPanel implements Observer {
	/**
	 * 
	 */
	private static final long serialVersionUID = 8610926037567455535L;

	private ArrayList<String> clients;

	private JTextArea drawerField;
	private JTextArea playerField;

	public UserList(int width, int height) {
		clients = new ArrayList<String>();
		setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		drawerField = new JTextArea();
		drawerField.setEditable(false);
		drawerField.setPreferredSize(new Dimension(width, 25));
		JPanel drawerPanel = new JPanel();
		drawerPanel.add(drawerField);
		drawerPanel.setBorder(BorderFactory.createTitledBorder(
				BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
				"Drawer"));
		add(drawerPanel, c);
		playerField = new JTextArea();
		playerField.setEditable(false);
		playerField.setPreferredSize(new Dimension(width, height - 25 * 2));
		JPanel playerPanel = new JPanel();
		playerPanel.add(playerField);
		playerPanel.setBorder(BorderFactory.createTitledBorder(
				BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
				"Guessers"));
		c.gridy = 1;
		add(playerPanel, c);
	}

	public void addUser(String id) {
		clients.add(id);
		updateList();
	}

	public void removeUser(String id) {
		String toRemove = "";

		for (String s : clients) {
			if (s.equals(id)) {
				toRemove = s;
				break;
			}
		}
		if (toRemove.equals("")) {
			clients.remove(toRemove);
		}
		updateList();
	}

	public void updateList() {
		String list = "";
		drawerField.setText(clients.get(0));
		for (int i = 1; i < clients.size(); i++) {
			list = list + clients.get(i) + "\n";
		}
		playerField.setText(list);
	}

	@Override
	public void update(Observable o, Object arg) {
		if (arg instanceof String[]) {
			System.out.println("Get new client list");
			String[] newClients = (String[]) arg;
			clients.clear();
			for (String s : newClients) {
				clients.add(s);
			}
			updateList();
		}

	}

}
